package com.sqx.modules.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.datacentre.entity.SysUserShop;
import com.sqx.modules.datacentre.service.ShopAdminService;
import com.sqx.modules.goods.entity.GoodsShop;
import com.sqx.modules.goods.service.GoodsShopService;
import com.sqx.modules.sys.entity.SysUserEntity;
import com.sqx.modules.sys.form.SysLoginForm;
import com.sqx.modules.sys.service.SysCaptchaService;
import com.sqx.modules.sys.service.SysUserService;
import com.sqx.modules.sys.service.SysUserTokenService;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 登录相关
 *
 */
@RestController
public class SysLoginController extends AbstractController {
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserTokenService sysUserTokenService;
	@Autowired
	private SysCaptchaService sysCaptchaService;
	@Autowired
	private GoodsShopService goodsShopService;
	@Autowired
	private ShopAdminService shopAdminService;
	@Autowired
	private UserService userService;


	/**
	 * 验证码
	 */
	@GetMapping("captcha.jpg")
	public void captcha(HttpServletResponse response, String uuid)throws IOException {
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");

		//获取图片验证码
		BufferedImage image = sysCaptchaService.getCaptcha(uuid);

		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
		IOUtils.closeQuietly(out);
	}

	/**
	 * 管理端登录
	 */
	@PostMapping("/sys/adminLogin")
	public Map<String, Object> login(@RequestBody SysLoginForm form)throws IOException {
		boolean captcha = sysCaptchaService.validate(form.getUuid(), form.getCaptcha());
		if(!captcha){
			return Result.error("验证码不正确");
		}

		//用户信息
		SysUserEntity user = sysUserService.queryByUserName(form.getUsername());

		//账号不存在、密码错误
		if(user == null || !user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
			return Result.error("账号或密码不正确");
		}

		//账号锁定
		if(user.getStatus() == 0){
			return Result.error("账号已被锁定,请联系管理员");
		}
		if(user.getUserType()==2){
			return Result.error("请前往商家端进行登录！");
		}

		//生成token，并保存到数据库
		Result r = sysUserTokenService.createToken(user.getUserId());
		return r;
	}


	/**
	 * 商户端登录
	 */
	@PostMapping("/sys/login")
	public Map<String, Object> shopLogin(@RequestBody SysLoginForm form)throws IOException {
		boolean captcha = sysCaptchaService.validate(form.getUuid(), form.getCaptcha());
		if(!captcha){
			return Result.error("验证码不正确");
		}

		//用户信息
		SysUserEntity user = sysUserService.queryByUserName(form.getUsername());

		//账号不存在、密码错误
		if(user == null || !user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
			return Result.error("账号或密码不正确");
		}

		//账号锁定
		if(user.getStatus() == 0){
			return Result.error("账号已被锁定,请联系管理员");
		}
		if(user.getUserType()==1){
			return Result.error("请前往管理端进行登录！");
		}
//		List<SysUserShop> sysUserShops = sysUserService.selectShopId(user.getUserId());
//		if(sysUserShops!=null && sysUserShops.size()>0 && sysUserShops.get(0).getBannedFlag()!=null && sysUserShops.get(0).getBannedFlag().equals(1)){
//			return Result.error("商铺已被封禁，请联系管理员！");
//		}
		SysUserShop sysUserShop = shopAdminService.getOne(new QueryWrapper<SysUserShop>().eq("user_id", user.getUserId()));
		GoodsShop goodsShop = goodsShopService.getOne(new QueryWrapper<GoodsShop>().eq("shop_id", sysUserShop.getShopId()));
		if(goodsShop==null){
			return Result.error("店铺不存在");
		}
		if (goodsShop.getBannedFlag() !=null && goodsShop.getBannedFlag() != 0) {
			return Result.error("商铺已被封禁，请联系管理员！");
		}
		if (goodsShop.getStatus() != 1) {
			return Result.error("当前店铺暂未通过审核");
		}
		if(StringUtils.isNotEmpty(form.getOpenId())){
			UserEntity userEntity = userService.selectUserById(goodsShop.getUserId());
			userEntity.setShopOpenId(form.getOpenId());
			userService.updateById(userEntity);
		}
		//生成token，并保存到数据库
		return sysUserTokenService.createToken(user.getUserId());
	}


	/**
	 * 退出
	 */
	@PostMapping("/sys/logout")
	public Result logout() {
		sysUserTokenService.logout(getUserId());
		return Result.success();
	}
	
}
